//
//  ViewController.swift
//  DocumentPickerDemo
//
//  Created by xthk_lmc on 2020/11/6.
//

import UIKit

class ViewController: UIViewController {

    
    var letdocument: UIDocumentPickerViewController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func onOpenDocumentPickerClicked(_ sender: Any) {
        selectUploadFileFromICouldDrive()
    }
    
    private func selectUploadFileFromICouldDrive()  {
        let documentTypes = ["public.content",
                             "public.text",
                             "public.source-code",
                             "public.image",
                             "public.audiovisual-content",
                             "com.adobe.pdf",
                             "com.apple.keynote.key",
                             "com.microsoft.word.doc",
                             "com.microsoft.excel.xls",
                             "com.microsoft.powerpoint.ppt"]

         let document = UIDocumentPickerViewController.init(documentTypes: documentTypes, in: .open)
         document.delegate = self  //UIDocumentPickerDelegate
         self.present(document, animated:true, completion:nil)
    }
    
}

extension ViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        
        let fileUrlAuthozied: Bool = (urls.first?.startAccessingSecurityScopedResource() ?? false)
        if fileUrlAuthozied {
            
            // 通过文件协调工具来得到新的文件地址，以此得到文件保护功能
            let fileCoordinator = NSFileCoordinator()
            fileCoordinator.coordinate(readingItemAt: urls.first ?? URL.init(fileURLWithPath: ""), options: NSFileCoordinator.ReadingOptions(rawValue: 0), error: nil) { (newURL) in
                print(newURL)
            }
            
            urls.first?.stopAccessingSecurityScopedResource()
            
        } else {
            print("授权失败")
        }
        
    }
}
